//
//  API_Discover.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/4.
//

import UIKit
import Moya

enum API_Discover {
    /// 全部
    case discover(String)
    /// banner
    case disBanner
    /// 热词
    case hotWord
    /// 搜索
    case search(String, Int)
    /// 标签书籍
    case tag(String, Int)
    /// 类型书籍
    case categocry(String, Int)
    /// 猜你喜欢
    case guesslike(Int)
}

let discover_timeoutClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<API_Discover>.RequestResultClosure) in
    do {
        var request = try endpoint.urlRequest()
        request.timeoutInterval = 5
        done(.success(request))
    }catch {
        return
    }
}

let provider_discover = MoyaProvider<API_Discover>(requestClosure: discover_timeoutClosure)

extension API_Discover: TargetType {
    var baseURL: URL {
        return URL(string: server.APIHost)!
    }
    
    var path: String {
        switch self {
        case .discover(_):
            return "/Article/home"
        case .disBanner:
            return "/Article/getBanner"
        case .hotWord:
            return "/Article/hotsearch"
        case .search(_, _):
            return "/Article/search"
        case .tag(_, _):
            return "/Article/category_book"
        case .categocry(_, _):
            return "/Article/category_book"
        case .guesslike(_):
            return "/Article/getUlike"
        }
    }
    
    var method: Moya.Method {
        return .post
    }
    
    var parameterEncoding: ParameterEncoding {
        return JSONEncoding.default
    }
    
    var sampleData: Data {
        return "test".data(using: String.Encoding.utf8)!
    }
    
    var task: Task {
        var ps: [String: Any] = ["ver": getAPPVersion(), "channel": "ios", "third_channel": "apple", "timestamp": Date().timeStamp, "userId": getUser()?.userId ?? "", "uuid": getKeyUUId(), "user_channel": getADID()]
        switch self {
        case .discover(let type):
            ps["type"] = type
        case .disBanner, .hotWord:
            break
        case .search(let keyword, let page):
            ps["keyword"] = keyword
            ps["page"] = page
            ps["num"] = 10
        case .tag(let tag, let page):
            ps["tag"] = tag
            ps["page"] = page
            ps["num"] = 10
        case .categocry(let category, let page):
            ps["category"] = category
            ps["page"] = page
            ps["num"] = 10
        case .guesslike(let page):
            ps["page"] = page
            ps["num"] = 10
        }
        return .requestParameters(parameters: ps, encoding: JSONEncoding.default)
    }
    
    var headers: [String : String]? {
        return ["content-type": "application/json; charset=UTF-8"]
    }
}
